<?php

abstract class Admin_Library_Controller_Action extends APPCore_Admin_Controller_Action
{

    protected $_acl = array();
    protected $_model;
    protected $_form;
    protected $_params = null;
    protected $_page = 1;
    protected $_limit = 10;
    protected $_orders = array();
    protected $_wheres = array();
    protected $_orWheres = array();
    protected $_likes = array();
    protected $_orLikes = array();
    protected $_defaultUrlOptions = array();
    
    public function init()
    {
    	parent::init();
    	
    	if (!in_array($this->_request->getActionName(), array('login', 'logout', 'get-salt'))) {
    	    $userProfile = $this->view->userProfile;
    	    $this->_acl = new APPCore_Acl_Acl($userProfile['username']);
    	    if (! $this->_acl->isUserAllowed($this->getRequest()->getModuleName() . '-' . $this->getRequest()->getControllerName(), $this->getRequest()->getActionName())) {
    	        $urlOptions = array('module'=>'admin', 'controller'=>'error', 'action'=>'restricted');
    	        $this->_helper->redirector->gotoRoute($urlOptions);
    	    }
    	}
    	
    	$this->view->themePath = $this->view->baseUrl() . '/themes/appcore';
    
    	// Load CSS
    	$this->view->headLink()->appendStylesheet($this->view->themePath . '/css/bootstrap.css');
    	$this->view->headLink()->appendStylesheet($this->view->themePath . '/css/bootstrap-responsive.css');
    	$this->view->headLink()->appendStylesheet($this->view->themePath . '/css/prettify.css');
    	$this->view->headLink()->appendStylesheet($this->view->themePath . '/css/admin.css');
    
    	// Load JS
    	$this->view->headScript()->appendFile($this->view->themePath . '/js/jquery-1.7.2.min.js', 'text/javascript');
    	$this->view->headScript()->appendFile($this->view->themePath . '/js/bootstrap.min.js', 'text/javascript');
    	$this->view->headScript()->appendFile($this->view->themePath . '/js/prettify.js', 'text/javascript');
    	$this->view->headScript()->appendFile($this->view->themePath . '/js/function.js', 'text/javascript');
    	$this->view->headScript()->appendFile($this->view->themePath . '/js/common.js', 'text/javascript');
    
    	// fav and touch icons
    	$arr = array('rel' => 'shortcut icon', 'href' => $this->view->baseUrl() . '/favicon.ico', 'type' => 'image/x-icon');
    	$this->view->headLink($arr, 'PREPEND');
    	$arr = array('rel' => 'apple-touch-icon-precomposed', 'href' => $this->view->themePath . '/ico/apple-touch-icon-144-precomposed.png', 'sizes' => '144x144');
    	$this->view->headLink($arr, 'PREPEND');
    	$arr = array('rel' => 'apple-touch-icon-precomposed', 'href' => $this->view->themePath . '/ico/apple-touch-icon-72-precomposed.png', 'sizes' => '72x72');
    	$this->view->headLink($arr, 'PREPEND');
    	$arr = array('rel' => 'apple-touch-icon-precomposed', 'href' => $this->view->themePath . '/ico/assets/ico/apple-touch-icon-57-precomposed.png', 'sizes' => '57x57');
    	$this->view->headLink($arr, 'PREPEND');
    
    	$this->view->headMeta()->appendName('viewport', 'width=device-width, initial-scale=1.0');
    
    	$userProfile = $this->view->userProfile;
    	//Check role of user. If user's role is 1 or 2 then to allow user access to backend.
    	if (!empty($userProfile['username'])) {
    		$modelUser = new Model_User();
    		$userRole = $modelUser->getRoleUser($this->view->userProfile['id']);
    		Zend_Registry::set('userRole', $userRole);
    		if (is_array($userRole) && count($userRole) > 0) {
    			$userProfile['roleId'] = $userRole ['role_id'];
    			$userProfile['roleName'] = $userRole ['role_name'];
    			$this->view->userProfile = $userProfile;
    			$this->userProfile = $userProfile;
    		}
    	}
    
    	$this->_helper->layout->setLayout('admin');
    
    	$this->view->moduleName = $this->getRequest()->getModuleName();
    	$this->view->controllerName = $this->getRequest()->getControllerName();
    	$this->view->actionName = $this->getRequest()->getActionName();
    
    	$this->_params = $this->getRequest()->getParams();
    	if ($this->getRequest()->isPost()) {
    		$this->_params = array_merge($this->_params, $this->getRequest()->getPost());
    	}
    
    	$this->_defaultUrlOptions = array(
    			'module' => $this->getRequest()->getModuleName(),
    			'controller' => $this->getRequest()->getControllerName(),
    			'action' => 'list'
    	);
    }

    public function listAction()
    {
        $total = $this->_model->getTotal($this->_wheres, $this->_orWheres, $this->_likes, $this->_orLikes);
        if ($total > 0 && (ceil($total / $this->_limit) < $this->_page)) {
            $msg = array(
                'result' => 'info',
                'message' => $this->view->translate('MSG_WARNING_ITEMS_OUT_OF_RANKING')
            );
            $this->_helper->flashMessenger->addMessage($msg);
            // redirect
            $this->_helper->redirector->gotoRoute($this->_defaultUrlOptions, 'default', true);
        }

        $items = $this->_model->getListItems($this->_page, $this->_limit, $this->_wheres, $this->_orders, $this->_orWheres, $this->_likes, $this->_orLikes);
        $this->view->assign('items', $items);

        //pagination start
        $this->view->assign('item_per_page', $this->_limit);
        //$this->view->assign('list_item_perpage', $configItemPage);
        $this->view->assign('page', $this->_page);
        $this->view->assign('order', $this->_orders);
        $this->view->assign('total', $total);
        $this->view->assign(
                'pagination_config', array(
            'total_items' => $total,
            'items_per_page' => $this->_limit,
            'style' => $this->view->config->site->backend->paging->style
                )
        );
    }

    public function cancelAction()
    {
        $msg = array(
            'result' => 'info',
            'message' => $this->view->translate('MSG_INFO_ACTION_CANCEL')
        );
        $this->_helper->flashMessenger->addMessage($msg);

        // redirect
        $this->_helper->redirector->gotoRoute($this->_defaultUrlOptions, 'default', true);
    }

    public function deleteAction()
    {
        $options = array(
            'select' => 'delete',
            'id' => $this->getRequest()->getParam('id')
        );
        $this->_forward('bulk', $this->getRequest()->getControllerName(), $this->getRequest()->getModuleName(), $options);
    }

    public function bulkAction()
    {
        // Start
        $ids = array();

        // merge id
        if ($this->getRequest()->getParam('id') > 0) {
            $ids[] = $this->getRequest()->getParam('id');
        }
        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();
            $ids = array_merge($ids, $post['list_items']);
        }

        if (count($ids)) {
            $result = array();
            switch ($this->getRequest()->getParam('select')) {
                case 'delete':
                    $result = $this->delete($ids);
                    $this->_helper->flashMessenger->addMessage($result);
                    break;
                case 'published':
                    $result = $this->published($ids, $this->getRequest()->getParam('value'));
                    $this->_helper->flashMessenger->addMessage($result);
                    break;
                default:
                    break;
            }
        } else {
            $msg = array(
                'result' => 'info',
                'message' => $this->view->translate('MSG_INFO_NO_ITEMS_SELECTED')
            );
            $this->_helper->flashMessenger->addMessage($msg);
        }

        // redirect
        $this->_helper->redirector->gotoRoute($this->_defaultUrlOptions, 'default', true);
    }

    protected function save()
    {
        $msg = array();
        if (is_object($this->_model)) {
            try {
                $attributes = $this->_model->buildAttributes($this->getRequest()->getParams());
                $this->_model->setOptions($attributes);
                $result = $this->_model->save();
                if ($result) {
                    $msg = array(
                        'result' => 'success',
                        'message' => $this->view->translate('MSG_SUCCESS_SAVE')
                    );
                } else {
                    $msg = array(
                        'result' => 'failed',
                        'message' => $this->view->translate('MSG_FAILED_SAVE')
                    );
                }
            } catch (Zend_Exception $e) {
                $msg = array(
                    'result' => 'failed',
                    'message' => $e->getMessage()
                );
            }
        } else {
            $msg = array(
                'result' => 'error',
                'message' => $this->view->translate('MSG_ERROR_MODEL_NOT_INITIAL')
            );
        }

        return $msg;
    }

    private function delete($ids)
    {
        $msg = array();
        if (is_object($this->_model)) {
            try {
                $numRows = $this->_model->delete($ids);
                $msg = array(
                    'result' => 'success',
                    'message' => sprintf($this->view->translate('MSG_SUCCESS_DELETE'), $numRows)
                );
            } catch (Zend_Exception $exc) {
                $msg = array(
                    'result' => 'error',
                    'message' => $exc->getMessage()
                );
            }
        } else {
            $msg = array(
                'result' => 'error',
                'message' => $this->view->translate('MSG_ERROR_MODEL_NOT_INITIAL')
            );
        }

        return $msg;
    }

    private function published($ids, $value)
    {
        $msg = array();
        if (is_object($this->_model)) {
            try {
                $numRows = $this->_model->updatePublished($ids, $value);
                $msg = array(
                    'result' => 'success',
                    'message' => sprintf($this->view->translate('MSG_SUCCESS_UPDATE'), $numRows)
                );
            } catch (Zend_Exception $exc) {
                $msg = array(
                    'result' => 'error',
                    'message' => $exc->getMessage()
                );
            }
        } else {
            $msg = array(
                'result' => 'error',
                'message' => $this->view->translate('MSG_ERROR_MODEL_NOT_INITIAL')
            );
        }

        return $msg;
    }

}